import 'package:flutter/material.dart';
import 'package:loxen/api/http_server/dictionaries.dart';
import 'package:loxen/api/http_server/report.dart';
import 'package:loxen/api/http_server/statistics.dart';
import 'package:loxen/dialog/board_dialog.dart';
import 'package:loxen/dialog/share_dialog.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/comment_mode.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/photo_view_simple_screen.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:loxen/mode/inspiration/inspiration_info_bean.dart';
import 'package:loxen/mode/material/material_item.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/format_time.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/viewmode/inspiration_detail_viewmodel.dart';
import 'package:loxen/viewmode/login_view_model.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:loxen/widget/triangle_painter.dart';

import 'comment_input_widget.dart';

enum CommentType {
  COMMENT, //评论
  COMMENT_TO_USER, //回复
}

class CommentValueData {
  bool _commentIsHide;
  String _hintText;
  CommentType _type;
  Comment _comment;
  Comment params;

  CommentValueData(this._commentIsHide, this._hintText, this._type, this._comment, {this.params});

  Comment get comment => _comment;

  CommentType get type => _type;

  String get hintText => _hintText;

  bool get commentIsHide => _commentIsHide;
}

// ignore: must_be_immutable
class InspirationDetailWidget extends StatelessWidget with StatisticsMixin {
  final blue = const Color(0xFF0CABCB);
  final grey = const Color(0xFF999999);
  final InspirationInfo detail;
  final CommentValueData hide = CommentValueData(true, '', null, null);
  final ValueNotifier<CommentValueData> commentIsHide =
      ValueNotifier(CommentValueData(true, '', null, null));
  final FocusNode _commentFocus = FocusNode();
  final ScrollController scrollController = ScrollController();
  String hintText;
  FocusScopeNode _focusScope;

  InspirationDetailWidget({
    Key key,
    this.detail,
  }) : super(key: key) {
    statisticeIdeaArticle(detail.id.toString());
  }

  @override
  Widget build(BuildContext context) {
    _focusScope = FocusScope.of(context);
    return ChangeNotifierProvider<InspirationDetailViewMode>(
      create: (BuildContext context) {
        InspirationDetailViewMode model = InspirationDetailViewMode(detail);
        model.loadData();
        scrollController.addListener(() {
          if (commentIsHide.value.commentIsHide == false) {
            commentIsHide.value = hide;
            _focusScope.unfocus();
          }
          model.changeColor(scrollController.offset);
        });
        return model;
      },
      child: Scaffold(
        extendBodyBehindAppBar: true,
        appBar: PreferredSize(
          preferredSize: Size(double.infinity, 95.h),
          child: Selector<InspirationDetailViewMode, int>(
            builder: (context, opacity, __) {
              return Container(
                color: Theme.of(context).primaryColor.withAlpha(opacity),
                child: SafeArea(
                  child: Row(
                    children: <Widget>[
                      MySubassembly.getBackIcon(context),
                      Expanded(
                        child: Builder(builder: (context) {
                          BaseState state = context.select<InspirationDetailViewMode, BaseState>(
                              (value) => value.mState);
                          if (state == BaseState.CONTENT) {
                            return Center(
                              child: Text(
                                Provider.of<InspirationDetailViewMode>(context).contentBean.title,
                                maxLines: 1,
                                style: TextStyle(
                                    fontSize: 31.sp, color: Colors.white.withAlpha(opacity)),
                              ),
                            );
                          } else {
                            return Constants.empty;
                          }
                        }),
                      ),
                      Builder(builder: (context) {
                        return MySubassembly.getSearchIcon(() {
                          if (context.read<InspirationDetailViewMode>().mState != BaseState.CONTENT)
                            return;
                          showDialog(
                              context: context,
                              builder: (_) => ShareDialog(
                                    info: context.read<InspirationDetailViewMode>().contentBean,
                                  ));
                        }, url: 'images/unfold_white.png', width: 44.w, height: 8.h);
                      }),
                    ],
                  ),
                ),
              );
            },
            selector: (_, model) => model.opacity,
            shouldRebuild: (old, next) => old != next,
          ),
        ),
        body: Selector<InspirationDetailViewMode, BaseState>(
            builder: (context, state, __) {
              print('content Build');
              if (state == BaseState.LOADING) {
                return LoadingWidget();
              }
              if (state == BaseState.CONTENT) {
                return MediaQuery.removePadding(
                  context: context,
                  removeTop: true,
                  child: Container(
                    color: Theme.of(context).backgroundColor,
                    child: Stack(
                      children: <Widget>[
                        ListView.builder(
                            controller: scrollController,
                            physics: ClampingScrollPhysics(),
                            itemCount: 1,
                            itemBuilder: (context, index) => Column(
                                  children: <Widget>[
                                    _getContentWidget(context, 0),
                                    _getContentWidget(context, 1),
                                    _getContentWidget(context, 2),
                                    _getContentWidget(context, 3),
                                    _getContentWidget(context, 4),
                                    _getContentWidget(context, 5),
                                    _getContentWidget(context, 6),
                                    _getContentWidget(context, 7),
                                  ],
                                )),
                        Align(
                          alignment: Alignment.bottomCenter,
                          child: Padding(
                            padding: EdgeInsets.only(bottom: 50.h),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisSize: MainAxisSize.max,
                              children: <Widget>[
                                Padding(
                                  padding: EdgeInsets.only(left: 36.w),
                                  child: _customButton(
                                      iconPath: 'images/comment_icon.png',
                                      selectedIconPath: 'images/comment_icon.png',
                                      onPressed: () {
                                        moveCommentTop(context);
                                        if (context.read<LoginViewModel>().isLogin()) {
                                          Navigator.of(context).pushNamed(Routes.login_page);
                                        } else {
                                          commentIsHide.value = CommentValueData(
                                              false, '评论：', CommentType.COMMENT, null);
                                          _focusScope.requestFocus(_commentFocus);
                                        }
                                      }),
                                ),
                                Expanded(child: Constants.empty),
                                Selector<InspirationDetailViewMode, int>(
                                    builder: (context, data, __) {
                                      return _customButton(
                                          iconPath: 'images/collation_false.png',
                                          selectedIconPath: 'images/collation_true.png',
                                          isSelected: data == 1,
                                          onPressed: () async {
                                            if (context.read<LoginViewModel>().isLogin()) {
                                              Navigator.of(context).pushNamed(Routes.login_page);
                                              return;
                                            }
                                            if (data == 1) {
                                              bool data = await showDialog(
                                                  context: context,
                                                  builder: (context) => AlertDialog(
                                                        title: Text('提示'),
                                                        content: Text(
                                                          '是否取消收藏？',
                                                          style: TextStyle(color: Colors.black),
                                                        ),
                                                        actions: <Widget>[
                                                          FlatButton(
                                                            child: Text(StringResources.qu_xiao),
                                                            onPressed: () =>
                                                                Navigator.of(context).pop(),
                                                          ),
                                                          FlatButton(
                                                            child: Text(StringResources.que_ding),
                                                            onPressed: () {
                                                              Navigator.of(context).pop(true);
                                                            },
                                                          ),
                                                        ],
                                                      ));
                                              if (data != null && data) {
                                                context
                                                    .read<InspirationDetailViewMode>()
                                                    .unCollectionArticle(
                                                        onShow: (msg) => Toast.show(msg, context));
                                              }
                                            } else {
                                              Navigator.of(context)
                                                  .pushNamed(Routes.master_file_add, arguments: {
                                                'type': FileType.INSPIRATION,
                                                'id': detail.id.toString()
                                              }).then((value) {
                                                if (value) {
                                                  context
                                                      .read<InspirationDetailViewMode>()
                                                      .collectionArticle();
                                                }
                                              });
                                            }
                                          });
                                    },
                                    selector: (_, model) => model.contentBean.is_collect),
                                Padding(
                                  padding: EdgeInsets.only(left: 40.w, right: 36.w),
                                  child: Selector<InspirationDetailViewMode, int>(
                                      builder: (context, data, __) {
                                        return _customButton(
                                            iconPath: 'images/like_false.png',
                                            selectedIconPath: 'images/like_true.png',
                                            isSelected: data == 1,
                                            onPressed: () {
                                              if (context.read<LoginViewModel>().isLogin()) {
                                                Navigator.of(context).pushNamed(Routes.login_page);
                                              } else {
                                                if (data == 0) {
                                                  context
                                                      .read<InspirationDetailViewMode>()
                                                      .likeThis();
                                                } else {
                                                  context
                                                      .read<InspirationDetailViewMode>()
                                                      .unLikeThis();
                                                }
                                              }
                                            });
                                      },
                                      selector: (_, model) => model.contentBean.is_like),
                                )
                              ],
                            ),
                          ),
                        ),
                        ValueListenableProvider.value(
                          value: commentIsHide,
                          builder: (context, _) {
                            CommentValueData data = context.watch<CommentValueData>();
                            return Offstage(
                              offstage: data.commentIsHide,
                              child: Align(
                                alignment: Alignment.bottomCenter,
                                child: CommentInputWidget(
                                  onTapComment: (text) {
                                    if (data.type == CommentType.COMMENT) {
                                      context.read<InspirationDetailViewMode>().commentThis(text,
                                          onError: (msg) => Toast.show(msg, context));
                                    } else {
                                      context.read<InspirationDetailViewMode>().commentToComment(
                                          data.comment, "${data.hintText}:$text",
                                          params: data.params,
                                          onError: (msg) => Toast.show(msg, context));
                                    }
                                    commentIsHide.value = hide;
                                    _focusScope.unfocus();
                                  },
                                  commentFocus: _commentFocus,
                                  hintText: data.hintText,
                                ),
                              ),
                            );
                          },
                        )
                      ],
                    ),
                  ),
                );
              }
              if (state == BaseState.FAIL) {
                return FailWidget(
                  onClick: () {
                    context.read<InspirationDetailViewMode>().loadData();
                  },
                );
              }
              return Text('');
            },
            shouldRebuild: (old, next) => old != next,
            selector: (_, model) => model.mState),
      ),
    );
  }

  Widget _customButton({iconPath, selectedIconPath, isSelected = false, onPressed}) {
    return InkWell(
      onTap: onPressed,
      child: AnimatedCrossFade(
        duration: Duration(milliseconds: 200),
        firstChild: Image.asset(
          iconPath,
          width: 108.w,
          height: 108.w,
        ),
        secondChild: Image.asset(
          selectedIconPath,
          width: 108.w,
          height: 108.w,
        ),
        crossFadeState: isSelected ? CrossFadeState.showSecond : CrossFadeState.showFirst,
      ),
    );
  }

  //主体内容
  Widget _getContentWidget(BuildContext context, int index) {
    switch (index) {
      case 0: //封面图
        return CachedNetworkImage(
          imageUrl:
              ImageUrlUtil.getClean(context.read<InspirationDetailViewMode>().contentBean.cover),
          width: 750.w,
          height: 550.h,
          placeholder: (_, __) => Constants.loadingIcon(),
          fit: BoxFit.cover,
        );
      case 1: //个人信息
        return Container(
          padding: EdgeInsets.only(top: 31.h, left: 37.w, right: 36.w),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              headClipRRect(
                  context.read<InspirationDetailViewMode>().contentBean.user.portrait, 83.w, () {
                Navigator.of(context)
                    .pushNamed(Routes.mine_user_info,
                        arguments: context
                            .read<InspirationDetailViewMode>()
                            .contentBean
                            .user
                            .userId
                            .toString())
                    .then((value) => context.read<InspirationDetailViewMode>().loadData());
              }),
              Expanded(
                child: Padding(
                  padding: EdgeInsets.only(left: 20.w),
                  child: Text(
                    context.read<InspirationDetailViewMode>().contentBean.user.nickname,
                    style: TextStyle(fontSize: 29.sp, fontWeight: FontWeight.w600),
                  ),
                ),
              ),
              Selector<InspirationDetailViewMode, int>(
                builder: (context, data, __) {
                  return Container(
                    margin: EdgeInsets.only(top: 9.h),
                    width: 125.w,
                    height: 49.h,
                    decoration: BoxDecoration(
                      border: Border.all(color: data == 1 ? blue : grey, width: 1.w),
                      borderRadius: BorderRadius.circular(4.w),
                    ),
                    child: FlatButton(
                        padding: EdgeInsets.all(0),
                        onPressed: () {
                          if (context.read<LoginViewModel>().isLogin()) {
                            Navigator.of(context).pushNamed(Routes.login_page);
                          } else {
                            if (data == 0) {
                              context
                                  .read<InspirationDetailViewMode>()
                                  .followThisUser(onError: (msg) => Toast.show(msg, context));
                            } else {
                              context
                                  .read<InspirationDetailViewMode>()
                                  .unFollowThisUser(onError: (msg) => Toast.show(msg, context));
                            }
                          }
                        },
                        child: Text(
                          data == 1 ? '已关注' : '关注',
                          maxLines: 1,
                          style: TextStyle(fontSize: 23.sp, color: data == 1 ? blue : grey),
                        )),
                  );
                },
                selector: (_, model) => model.contentBean.user.isFollowed,
              )
            ],
          ),
        );
      case 2: //文章标题 阅读 点赞 评论 时间展示
        return Padding(
          padding: EdgeInsets.only(left: 37.w, right: 36.w, top: 45.h, bottom: 40.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                width: 537.w,
                child: Text(
                  context.read<InspirationDetailViewMode>().contentBean.title,
                  maxLines: 2,
                  style: TextStyle(fontSize: 30.sp, fontWeight: FontWeight.w800),
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 32.h),
                child: Row(
                  children: <Widget>[
                    Expanded(
                        child: Text(
                      FormatTime.readTimestamp(
                          context.read<InspirationDetailViewMode>().contentBean.add_time),
                      style: TextStyle(
                          color: Color(0xFF999999), fontSize: 22.sp, fontWeight: FontWeight.w500),
                    )),
                    Builder(builder: (context) {
                      var data = context.select<InspirationDetailViewMode, int>(
                          (value) => value.contentBean.view_num);
                      return tag('images/eye.png', "$data", 31.w, 26.h, 23.sp);
                    }),
                    Builder(builder: (context) {
                      var data = context.select<InspirationDetailViewMode, int>(
                          (value) => value.contentBean.like_num);
                      return Padding(
                        padding: EdgeInsets.only(left: 29.w),
                        child: tag('images/like.png', "$data", 30.w, 30.w, 23.sp),
                      );
                    }),
                    Builder(builder: (context) {
                      var data = context.select<InspirationDetailViewMode, int>(
                          (value) => value.contentBean.comment_num);
                      return Padding(
                        padding: EdgeInsets.only(left: 29.w),
                        child: tag('images/comment.png', "$data", 30.w, 30.w, 23.sp),
                      );
                    }),
                  ],
                ),
              )
            ],
          ),
        );
      case 3:
        return Divider(height: 1);
      case 4: //文章内容
        return createContent(context.read<InspirationDetailViewMode>().contentBean.contentList,
            onClick: (src) {
          List<String> list = context
              .read<InspirationDetailViewMode>()
              .contentBean
              .contentList
              .where((element) => element.startsWith('http'))
              .toList();
          Navigator.push(
            context,
            new MaterialPageRoute(
                builder: (context) => PhotoViewSimpleScreen(
                      imagePath: src,
                      images: list,
                      heroTag: 'simple',
                    )),
          );
        }, onLongClick: (src) async {
          if (context.read<LoginViewModel>().isLogin()) {
            Navigator.of(context).pushNamed(Routes.login_page);
            return;
          }
          bool success = await showDialog(
              context: context,
              builder: (_) => BoardDialog(
                    path: src,
                  ));
          if (success != null && success) {
            Toast.show('收藏完成', context);
          }
        });
      case 5: //关联素材
        return _getMaterial(context);
      case 6: //评论内容
        return Builder(builder: (context) {
          var count = context.select<InspirationDetailViewMode, List>((value) => value.comments);
          if (count != null && count.length > 0) {
            return _createComment(context);
          } else {
            return Constants.empty;
          }
        });
      case 7:
        return Selector<InspirationDetailViewMode, List<InspirationInfo>>(
            builder: (context, data, __) {
              if (data != null && data.length > 0) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      height: 20.h,
                      color: Color(0xFFF2F2F2),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 35.w, top: 60.h, bottom: 40.h),
                      child: Text(
                        '猜你喜欢',
                        style: TextStyle(fontSize: 30.sp, fontWeight: FontWeight.bold),
                      ),
                    ),
                    _getLikeItem(context, data)
                  ],
                );
              } else {
                return Constants.empty;
              }
            },
            shouldRebuild: (old, next) => old != next,
            selector: (_, model) => model.likeInspirations);
    }
    return Constants.empty;
  }

  //关联素材
  Widget _getMaterial(BuildContext context) {
    var info = context.read<InspirationDetailViewMode>().contentBean.products;
    if (info != null && info.length > 0) {
      return Container(
        margin: EdgeInsets.only(left: 37.w, right: 37.w,top: 30.h),
        width: double.infinity,
        height: 126.h,
        child: GridView.count(
          mainAxisSpacing: 10.w,
          crossAxisCount: 1,
          scrollDirection: Axis.horizontal,
          children: _itemImage(context, info),
        ),
      );
    } else {
      return Constants.empty;
    }
  }

  List<Widget> _itemImage(BuildContext context, List<MaterialItem> materials) {
    return materials
        .map((entity) => InkWell(
              onTap: () {
                Navigator.of(context).pushNamed(Routes.material_detail, arguments: entity.id);
              },
              child: Stack(
                alignment: Alignment.center,
                children: <Widget>[
                  ClipRRect(
                      borderRadius: BorderRadius.circular(10.w),
                      child: CachedNetworkImage(
                        imageUrl: ImageUrlUtil.getClean(entity.cover, w: 130),
                        width: double.infinity,
                        height: double.infinity,
                        placeholder: (_, __) => Constants.loadingIcon(),
                        fit: BoxFit.cover,
                      )),
                  Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                      height: 32.h,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: Colors.black26,
                        borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(10.w),
                          bottomRight: Radius.circular(10.w),
                        ),
                      ),
                      child: Text(
                        entity.code,
                        style: TextStyle(
                            fontSize: 19.sp,
                            color: Theme.of(context).textTheme.subtitle1.color,
                            fontWeight: FontWeight.w500),
                      ),
                    ),
                  )
                ],
              ),
            ))
        .toList();
  }

  //猜你喜欢列表
  Widget _getLikeItem(BuildContext context, List<InspirationInfo> list) {
    List<Widget> widgets = list.map((entity) {
      return Column(
        children: <Widget>[
          Container(
            height: 450.h,
            child: GestureDetector(
              onTap: () {
                Navigator.of(context)
                    .pushNamed(Routes.inspiration_detail, arguments: entity)
                    .then((value) {
                  context.read<InspirationDetailViewMode>().changeEntity();
                });
              },
              child: CachedNetworkImage(
                imageUrl: ImageUrlUtil.getClean(entity.cover),
                width: double.infinity,
                height: 450.h,
                placeholder: (_, __) => Constants.loadingIcon(),
                fit: BoxFit.cover,
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 15.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Expanded(
                    child: Text(
                  entity.title,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 27.sp,
                    fontWeight: FontWeight.w500,
                  ),
                )),
                Text(
                  FormatTime.readTimestamp(entity.add_time),
                  style: TextStyle(
                      color: Color(0xFF999999), fontSize: 20.sp, fontWeight: FontWeight.w500),
                )
              ],
            ),
          ), //标题  时间
          Container(
            margin: EdgeInsets.only(bottom: 30.h),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Row(
                    children: <Widget>[
                      Container(
                          width: 52.w,
                          height: 52.w,
                          decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              image: DecorationImage(
                                  image: NetworkImage(
                                    entity?.user?.portrait,
                                  ),
                                  fit: BoxFit.cover))),
                      Padding(
                        padding: EdgeInsets.only(left: 15.w),
                        child: Text(
                          entity?.user?.nickname,
                          style: TextStyle(color: Color(0xFF82868E), fontSize: 21.sp),
                        ),
                      )
                    ],
                  ),
                ),
                Selector<InspirationDetailViewMode, int>(
                  builder: (context, data, ___) {
                    return Padding(
                      padding: EdgeInsets.only(right: 20.w),
                      child: SizedBox(
                        width: 72.w,
                        child: FlatButton(
                          padding: EdgeInsets.all(1.w),
                          onPressed: () {
                            if (context.read<LoginViewModel>().isLogin()) {
                              Navigator.of(context).pushNamed(Routes.login_page);
                            } else {
                              if (data == 0) {
                                context
                                    .read<InspirationDetailViewMode>()
                                    .likeToLikeInspiration(entity);
                              } else {
                                context
                                    .read<InspirationDetailViewMode>()
                                    .unLikeToLikeInspiration(entity);
                              }
                            }
                          },
                          child: Stack(
                            alignment: Alignment.centerLeft,
                            children: <Widget>[
                              Image.asset(
                                entity.is_like == 0 ? "images/like.png" : "images/like_active.png",
                                width: 30.w,
                                height: 30.w,
                                fit: BoxFit.cover,
                              ),
                              Padding(
                                padding: EdgeInsets.only(
                                  left: 37.w,
                                  top: 4.h,
                                ),
                                child: Text(
                                  '${entity.like_num}',
                                  style: TextStyle(
                                      fontSize: 22.sp,
                                      color: entity.is_like == 0
                                          ? Color(0xFF999999)
                                          : Color(0xFF0CABCB)),
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                  selector: (_, __) => entity.is_like,
                  shouldRebuild: (old, next) => old != next,
                ),
                Padding(
                  padding: EdgeInsets.only(right: 20.w),
                  child: SizedBox(
                    width: 72.w,
                    child: FlatButton(
                      padding: EdgeInsets.all(1.w),
                      onPressed: () {
                        Navigator.of(context)
                            .pushNamed(Routes.inspiration_detail, arguments: entity)
                            .then((value) {
                          context.read<InspirationDetailViewMode>().changeEntity();
                        });
                      },
                      child: Stack(
                        alignment: Alignment.centerLeft,
                        children: <Widget>[
                          Image.asset(
                            'images/comment.png',
                            width: 30.w,
                            height: 30.w,
                            fit: BoxFit.cover,
                          ),
                          Padding(
                            padding: EdgeInsets.only(
                              left: 37.w,
                              top: 4.h,
                            ),
                            child: Text(
                              '${entity.comment_num}',
                              style: TextStyle(fontSize: 22.sp, color: Color(0xFF999999)),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
                Builder(builder: (context) {
                  bool collection = context
                      .select<InspirationDetailViewMode, bool>((value) => entity.is_collect == 0);
                  return SizedBox(
                    width: 72.w,
                    child: FlatButton(
                      padding: EdgeInsets.all(1.w),
                      onPressed: () {
                        if (context.read<LoginViewModel>().isLogin()) {
                          Navigator.of(context).pushNamed(Routes.login_page);
                          return;
                        }
                        if (collection) {
                          Navigator.of(context).pushNamed(Routes.master_file_add, arguments: {
                            'type': FileType.INSPIRATION,
                            'id': entity.id.toString()
                          }).then((value) {
                            if (value) {
                              entity.is_collect = 1;
                              entity.collect_num += 1;
                              context.read<InspirationDetailViewMode>().changeEntity();
                            }
                          });
                        } else {
                          context.read<InspirationDetailViewMode>().likeUnCollection(entity);
                        }
                      },
                      child: Stack(
                        alignment: Alignment.centerLeft,
                        children: <Widget>[
                          Image.asset(
                            collection ? "images/collect.png" : "images/collected.png",
                            width: 30.w,
                            height: 30.w,
                            fit: BoxFit.cover,
                          ),
                          Padding(
                            padding: EdgeInsets.only(
                              left: 37.w,
                              top: 4.h,
                            ),
                            child: Text(
                              '${entity.collect_num}',
                              style: TextStyle(
                                  fontSize: 22.sp,
                                  color: collection ? Color(0xFF999999) : Color(0xFF0CABCB)),
                            ),
                          )
                        ],
                      ),
                    ),
                  );
                }),
              ],
            ),
          )
        ],
      );
    }).toList();
    return Padding(
      padding: EdgeInsets.only(left: 36.w, right: 36.w),
      child: Column(
        children: widgets,
      ),
    );
  }

  //评论列表
  Widget _createComment(BuildContext context) {
    var comment = context.watch<InspirationDetailViewMode>().comments;
    List<Widget> list = [
      Text(
        '评论(${context.select<InspirationDetailViewMode, int>((value) => value.commentCount)})',
        style: TextStyle(fontSize: 30.sp, fontWeight: FontWeight.bold),
      ),
      Padding(
        padding: EdgeInsets.only(top: 18.h, bottom: 48.h),
        child: Divider(
          height: 1,
        ),
      )
    ];
    for (int i = 0; i < comment.length; i++) {
      list.add(_commentItem(context, comment[i]));
      if (i < comment.length - 1) {
        list.add(Padding(
          padding: EdgeInsets.only(top: 30.h, bottom: 46.h),
          child: Divider(
            height: 1,
          ),
        ));
      } else {
        list.add(Builder(builder: (context) {
          var data =
              context.select<InspirationDetailViewMode, List>((value) => value.likeInspirations);
          if (data == null || data.length == 0) {
            return Padding(
              padding: EdgeInsets.only(top: 30.h, bottom: 200.h),
              child: Divider(
                height: 1,
              ),
            );
          } else {
            return Padding(
              padding: EdgeInsets.only(top: 30.h),
              child: Divider(
                height: 1,
              ),
            );
          }
        }));
      }
    }
    if (context.watch<InspirationDetailViewMode>().isNextComment) {
      list.removeLast();
      list.add(Padding(
        padding: EdgeInsets.only(top: 30.h, bottom: 30.h),
        child: Divider(
          height: 1,
        ),
      ));
      list.add(Container(
        padding: EdgeInsets.only(bottom: 40.h),
        width: double.infinity,
        child: Center(
          child: InkWell(
            onTap: () {
              context.read<InspirationDetailViewMode>().nextComment();
            },
            child: Text(
              '查看更多评论',
              style: TextStyle(fontSize: 20.sp, color: Color(0xFF999999)),
            ),
          ),
        ),
      ));
    }
    return Padding(
      padding: EdgeInsets.only(left: 37.w, top: 50.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: list,
      ),
    );
  }

  //一级品论样式
  Widget _commentItem(BuildContext context, Comment comment) {
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            headClipRRect(comment.user.portrait, 72.w, () {
              Navigator.of(context)
                  .pushNamed(Routes.mine_user_info, arguments: comment.user.userId.toString());
            }),
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: 18.w, right: 30.w),
                child: Text(
                  comment?.user?.nickname,
                  style: TextStyle(fontSize: 28.sp, fontWeight: FontWeight.bold),
                ),
              ),
            ), //评论头像 //昵称
            Builder(
              builder: (BuildContext context) {
                var info = Provider.of<LoginViewModel>(context, listen: false).info;
                var content = context.watch<InspirationDetailViewMode>().contentBean;
                List<PopupMenuEntry<int>> listWidget = [];
                if ((info != null && info?.user?.userId == content.user.userId) ||
                    (info?.user?.userId == comment.user.userId)) {
                  listWidget.add(PopupMenuItem(
                      value: 0,
                      child: Row(
                        children: <Widget>[
                          Image.asset(
                            'images/trash_can.png',
                            width: 30.w,
                            height: 30.w,
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 17.w),
                            child: Text(
                              '删除评论',
                              style: TextStyle(
                                fontSize: 28.sp,
                                fontWeight: FontWeight.w600,
                                color: Color(0xFF696C72),
                              ),
                            ),
                          )
                        ],
                      )));
                } else {
                  listWidget.add(PopupMenuItem(
                      value: 1,
                      child: Row(
                        children: <Widget>[
                          Image.asset(
                            'images/report.png',
                            width: 30.w,
                            height: 30.w,
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 17.w),
                            child: Text(
                              '举报评论',
                              style: TextStyle(
                                fontSize: 28.sp,
                                fontWeight: FontWeight.w600,
                                color: Color(0xFF696C72),
                              ),
                            ),
                          )
                        ],
                      )));
                }

                return Padding(
                    padding: EdgeInsets.only(right: 36.w),
                    child: Material(
                      child: PopupMenuButton<int>(
                        onSelected: (index) {
                          if (index == 0) {
                            context.read<InspirationDetailViewMode>().deleteCommentNotify(comment,
                                onError: (msg) => Toast.show(msg, context));
                          } else {
                            Navigator.of(context).pushNamed(Routes.report_page, arguments: {
                              'id': comment.id.toString(),
                              'reportType': ReportType.COMMENT
                            });
                          }
                        },
                        itemBuilder: (BuildContext context) {
                          return listWidget;
                        },
                        child: Text(
                          '···',
                          style: TextStyle(
                              letterSpacing: 5.w,
                              color: Color(0xFF999999),
                              fontSize: 33.sp,
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                    ));
              },
            )
          ],
        ),
        Container(
          width: double.infinity,
          child: Padding(
            padding: EdgeInsets.only(left: 90.w, top: 13.h, right: 36.w),
            child: Column(
              children: <Widget>[
                TextField(
                  minLines: 1,
                  maxLines: 50,
                  readOnly: true,
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 24.sp,
                    color: Theme.of(context).textTheme.subtitle2.color,
                  ),
                  decoration: InputDecoration(
                    contentPadding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                    border: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.white, width: 0),
                    ),
                    focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.white, width: 0),
                        borderRadius: BorderRadius.all(Radius.circular(0))),
                    enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.white, width: 0),
                        borderRadius: BorderRadius.all(Radius.circular(0))),
                  ),
                  controller: TextEditingController(text: comment.content),
                ),
              ],
            ),
          ),
        ), //评论内容
        Container(
          margin: EdgeInsets.only(left: 90.w),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Text(
                  FormatTime.readTimestamp(comment.add_time),
                  style: TextStyle(
                      color: Color(0xFF999999), fontSize: 22.sp, fontWeight: FontWeight.w500),
                ),
              ), //评论时间
              Padding(
                padding: EdgeInsets.only(right: 5.w),
                child: SizedBox(
                  width: 72.w,
                  child: FlatButton(
                    padding: EdgeInsets.all(1.w),
                    onPressed: () {
                      if (context.read<LoginViewModel>().isLogin()) {
                        Navigator.of(context).pushNamed(Routes.login_page);
                      } else {
                        commentIsHide.value = CommentValueData(false,
                            '回复@${comment.user.nickname}：', CommentType.COMMENT_TO_USER, comment);
                        _focusScope.requestFocus(_commentFocus);
                      }
                    },
                    child: Image.asset(
                      'images/comment.png',
                      width: 30.w,
                      height: 30.w,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),
              Selector<InspirationDetailViewMode, int>(
                builder: (context, data, ___) {
                  return Padding(
                    padding: EdgeInsets.only(right: 50.w),
                    child: SizedBox(
                      width: 72.w,
                      child: FlatButton(
                        padding: EdgeInsets.all(1.w),
                        onPressed: () {
                          if (context.read<LoginViewModel>().isLogin()) {
                            Navigator.of(context).pushNamed(Routes.login_page);
                          } else {
                            if (data == 0) {
                              context
                                  .read<InspirationDetailViewMode>()
                                  .likeCommentArticle(comment.id.toString(), () {
                                comment.is_like = 1;
                                comment.likes_num += 1;
                              });
                            } else {
                              context
                                  .read<InspirationDetailViewMode>()
                                  .unLikeCommentArticle(comment.id.toString(), () {
                                comment.is_like = 0;
                                comment.likes_num -= 1;
                              });
                            }
                          }
                        },
                        child: Stack(
                          alignment: Alignment.centerLeft,
                          children: <Widget>[
                            Image.asset(
                              data == 0 ? "images/like.png" : "images/like_active.png",
                              width: 30.w,
                              height: 30.w,
                              fit: BoxFit.cover,
                            ),
                            Padding(
                              padding: EdgeInsets.only(
                                left: 37.w,
                                top: 4.h,
                              ),
                              child: Text(
                                '${comment.likes_num}',
                                style: TextStyle(
                                    fontSize: 22.sp,
                                    color: data == 0 ? Color(0xFF999999) : Color(0xFF0CABCB)),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  );
                },
                selector: (_, __) => comment.is_like,
                shouldRebuild: (old, next) => old != next,
              ) //评论点赞
            ],
          ),
        ),
        Selector<InspirationDetailViewMode, List<Comment>>(
            builder: (context, data, __) {
              if (data != null && data.length > 0) {
                return _subComment(context, comment);
              } else {
                return Constants.empty;
              }
            },
            shouldRebuild: (old, next) => old != next,
            selector: (_, __) => comment.sub_comment)
      ],
    );
  }

  //二级评论
  Widget _subComment(BuildContext context, Comment comment) {
    var subComment = comment.sub_comment;
    List<Widget> list = [];
    for (int i = 0; i < subComment.length; i++) {
      Comment sub = subComment[i];
      list.add(Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              headClipRRect(sub.user.portrait, 72.w, () {
                Navigator.of(context)
                    .pushNamed(Routes.mine_user_info, arguments: sub.user.userId.toString());
              }),
              Expanded(
                child: Padding(
                  padding: EdgeInsets.only(left: 18.w, right: 30.w),
                  child: Text(
                    sub.user.nickname,
                    style: TextStyle(fontSize: 28.sp, fontWeight: FontWeight.bold),
                  ),
                ),
              ), //评论头像 //昵称
              Builder(builder: (context) {
                var info = Provider.of<LoginViewModel>(context, listen: false).info;
                var content = context.watch<InspirationDetailViewMode>().contentBean;
                List<PopupMenuEntry<int>> listWidget = [];
                if ((info != null && info?.user?.userId == content.user.userId) ||
                    (info?.user?.userId == sub.user.userId)) {
                  listWidget.add(PopupMenuItem(
                      value: 0,
                      child: Row(
                        children: <Widget>[
                          Image.asset(
                            'images/trash_can.png',
                            width: 30.w,
                            height: 30.w,
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 17.w),
                            child: Text(
                              '删除评论',
                              style: TextStyle(
                                fontSize: 28.sp,
                                fontWeight: FontWeight.w600,
                                color: Color(0xFF696C72),
                              ),
                            ),
                          )
                        ],
                      )));
                } else {
                  listWidget.add(PopupMenuItem(
                      value: 1,
                      child: Row(
                        children: <Widget>[
                          Image.asset(
                            'images/report.png',
                            width: 30.w,
                            height: 30.w,
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 17.w),
                            child: Text(
                              '举报评论',
                              style: TextStyle(
                                fontSize: 28.sp,
                                fontWeight: FontWeight.w600,
                                color: Color(0xFF696C72),
                              ),
                            ),
                          )
                        ],
                      )));
                }

                return Padding(
                    padding: EdgeInsets.only(right: 36.w),
                    child: PopupMenuButton<int>(
                      onSelected: (index) {
                        if (index == 0) {
                          context.read<InspirationDetailViewMode>().deleteCommentNotify(sub,
                              onError: (msg) => Toast.show(msg, context),
                              isSub: true,
                              params: comment);
                        } else {
                          Navigator.of(context).pushNamed(Routes.report_page, arguments: {
                            'id': sub.id.toString(),
                            'reportType': ReportType.COMMENT
                          });
                        }
                      },
                      itemBuilder: (BuildContext context) {
                        return listWidget;
                      },
                      child: Text(
                        '···',
                        style: TextStyle(
                            letterSpacing: 5.w,
                            color: Color(0xFF999999),
                            fontSize: 33.sp,
                            fontWeight: FontWeight.bold),
                      ),
                    ));
              })
            ],
          ),
          Container(
            width: double.infinity,
            child: Padding(
              padding: EdgeInsets.only(left: 90.w, top: 13.h, right: 36.w),
              child: TextField(
                minLines: 1,
                maxLines: 50,
                readOnly: true,
                style: TextStyle(
                  fontWeight: FontWeight.w600,
                  fontSize: 24.sp,
                  color: Theme.of(context).textTheme.subtitle2.color,
                ),
                decoration: InputDecoration(
                  contentPadding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.transparent, width: 0),
                  ),
                  focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.transparent, width: 0),
                      borderRadius: BorderRadius.all(Radius.circular(0))),
                  enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.transparent, width: 0),
                      borderRadius: BorderRadius.all(Radius.circular(0))),
                ),
                controller: TextEditingController(text: sub.content),
              ),
            ),
          ), //评论内容
          Container(
            margin: EdgeInsets.only(left: 90.w),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Expanded(
                  child: Text(
                    FormatTime.readTimestamp(sub.add_time),
                    style: TextStyle(
                        color: Color(0xFF999999), fontSize: 20.sp, fontWeight: FontWeight.w500),
                  ),
                ), //评论时间
                Padding(
                  padding: EdgeInsets.only(right: 5.w),
                  child: SizedBox(
                    width: 72.w,
                    child: FlatButton(
                      padding: EdgeInsets.all(1.w),
                      onPressed: () {
                        if (context.read<LoginViewModel>().isLogin()) {
                          Navigator.of(context).pushNamed(Routes.login_page);
                        } else {
                          commentIsHide.value = CommentValueData(
                              false, '回复:@${sub.user.nickname}', CommentType.COMMENT_TO_USER, sub,
                              params: comment);
                          _focusScope.requestFocus(_commentFocus);
                        }
                      },
                      child: Image.asset(
                        'images/comment.png',
                        width: 26.w,
                        height: 26.w,
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),
                Selector<InspirationDetailViewMode, int>(
                  builder: (context, data, ___) {
                    return Padding(
                      padding: EdgeInsets.only(right: 50.w),
                      child: SizedBox(
                        width: 72.w,
                        child: FlatButton(
                          padding: EdgeInsets.all(1.w),
                          onPressed: () {
                            if (context.read<LoginViewModel>().isLogin()) {
                              Navigator.of(context).pushNamed(Routes.login_page);
                            } else {
                              if (data == 0) {
                                context
                                    .read<InspirationDetailViewMode>()
                                    .likeCommentArticle(sub.id.toString(), () {
                                  sub.is_like = 1;
                                  sub.likes_num += 1;
                                });
                              } else {
                                context
                                    .read<InspirationDetailViewMode>()
                                    .unLikeCommentArticle(sub.id.toString(), () {
                                  sub.is_like = 0;
                                  sub.likes_num -= 1;
                                });
                              }
                            }
                          },
                          child: Stack(
                            alignment: Alignment.centerLeft,
                            children: <Widget>[
                              Image.asset(
                                data == 0 ? "images/like.png" : "images/like_active.png",
                                width: 25.w,
                                height: 25.w,
                                fit: BoxFit.cover,
                              ),
                              Padding(
                                padding: EdgeInsets.only(
                                  left: 37.w,
                                  top: 4.h,
                                ),
                                child: Text(
                                  '${sub.likes_num}',
                                  style: TextStyle(
                                      fontSize: 17.sp,
                                      color: data == 0 ? Color(0xFF999999) : Color(0xFF0CABCB)),
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                  selector: (_, __) => sub.is_like,
                  shouldRebuild: (old, next) => old != next,
                ) //评论点赞
              ],
            ),
          ),
        ],
      ));
      if (i < subComment.length - 1) {
        list.add(Divider(height: 1));
      }
    }
    if (context.watch<InspirationDetailViewMode>().isNextSubComment(comment)) {
      list.add(Container(
        padding: EdgeInsets.only(bottom: 40.h),
        width: double.infinity,
        child: Center(
          child: InkWell(
            onTap: () {
              context.read<InspirationDetailViewMode>().nextSubComment(comment);
            },
            child: Text(
              '更多${comment.sub_comment_num - comment.sub_comment.length}条回复',
              style: TextStyle(fontSize: 20.sp, color: Color(0xFF999999)),
            ),
          ),
        ),
      ));
    }
    return Stack(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(
            top: 41.h,
            left: 90.w,
            right: 36.w,
          ),
          color: Color(0xFFF6F6F8),
          width: double.infinity,
          child: Padding(
            padding: EdgeInsets.only(left: 37.w, top: 37.h),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: list,
            ),
          ),
        ),
        Positioned(
            top: 22.h,
            left: 150.w,
            child: CustomPaint(
              painter: TrianglePainter(
                strokeColor: Color(0xFFEFF0F4),
                strokeWidth: 24.w,
                paintingStyle: PaintingStyle.fill,
              ),
            ))
      ],
    );
  }

  //小tag数字标记
  Widget tag(String path, String text, double imageW, double imageH, double textS) {
    return Row(
      children: <Widget>[
        Image.asset(
          path,
          width: imageW,
          height: imageH,
        ),
        Padding(
          padding: EdgeInsets.only(left: 5.w),
          child: Text(
            text,
            style: TextStyle(
              fontSize: textS,
              color: Color(0xFF999999),
            ),
          ),
        )
      ],
    );
  }

  //头像
  ClipRRect headClipRRect(String url, double circular, Function() onClick) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(circular),
      child: GestureDetector(
        onTap: onClick,
        child: url != null && url.trim() != ''
            ? CachedNetworkImage(
                imageUrl: ImageUrlUtil.getClean(url, w: 100),
                height: circular,
                width: circular,
                fit: BoxFit.cover,
              )
            : Container(
                width: circular,
                height: circular,
              ),
      ),
    );
  }

  Widget createContent(List<dynamic> content,
      {Function(String url) onClick, Function(String url) onLongClick}) {
    if (content != null && content.length > 0) {
      return Padding(
        padding: EdgeInsets.only(top: 50.h),
        child: ListView.builder(
          itemCount: content.length,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (_, index) {
            var e = content[index];
            if (e.startsWith('http')) {
              return GestureDetector(
                onTap: () {
                  onClick.call(e);
                },
                onLongPress: () {
                  onLongClick.call(e);
                },
                child: CachedNetworkImage(
                  imageUrl: ImageUrlUtil.getClean(e),
                  width: 750.w,
                  // height: e.ratio == 0 ? 0 : 750.w / e.ratio,
                  fit: BoxFit.cover,
                ),
              );
            } else {
              return Padding(
                padding: EdgeInsets.only(left: 30.w, right: 30.w, bottom: 10.h, top: 10.h),
                child: Text(
                  e,
                  style: TextStyle(fontSize: 24.sp, color: Colors.black),
                ),
              );
            }
          },
        ),
      );
    } else {
      return Text('内容为空');
    }
  }

  void moveCommentTop(BuildContext context) {
    int comm = 0;
    context.read<InspirationDetailViewMode>().comments.forEach((element) {
      comm += 130;
      element.sub_comment?.forEach((element) {
        comm += 130;
      });
    });
    var like = context.read<InspirationDetailViewMode>().likeInspirations?.length ?? 0 * 495;
    var jumpTo = scrollController.position.maxScrollExtent - like - comm;
    if (jumpTo > 0) {
      scrollController.jumpTo(jumpTo);
    }
  }
}
